package com.upsuns.lancher;

import java.util.Scanner;

import com.upsuns.entity.FileEntity;
import com.upsuns.fileop.FileInfoReader;
import com.upsuns.multiop.ThreadBatch;
import com.upsuns.protocol.Protocol;
import com.upsuns.protocol.ProtocolClient;
import com.upsuns.protocol.ProtocolServer;
import com.upsuns.utils.Constants;

/**
 *@Description:<p>守护线程启动</p>
 *@author 王旭
 *@time 2016-1-31 下午6:43:08
 */
public class Lancher {
	
	public static Scanner scan = new Scanner(System.in);
	
	public static void main(String[] args) {
		
		
		System.out.println("1--------发送文件");
		System.out.println("2--------接收文件");
		
		int menu1 = scan.nextInt();
		if(menu1 == 1) {
			sentMain();
		}
		else if(menu1 == 2){
			receiveMain();
		}
		else {
			System.out.println("输入有误");
		}
		
		
	}
	
	public static void sentMain() {
		
		
		Constants.TASK_TYPE = "SENT";
		System.out.println("输入接收方的地址：");
		Constants.ADDRESS = scan.next();
		System.out.println("输入要发送文件的绝对路径：");
		String path = scan.next();
		FileInfoReader fr = new FileInfoReader(path);
		FileEntity fe = fr.getFileEntity();
		
		//发送协议
		System.out.println("正在建立连接...");
		ProtocolClient pc = new ProtocolClient(Constants.ADDRESS);
		pc.sentProtocol(new Protocol(fe.getFileName(), fe.getFileSize()));
		
		long sentStartTime = System.currentTimeMillis();
		
		System.out.println("正在传输数据...");
		ThreadBatch tb = new ThreadBatch(fe);
		
		tb.startAll();
	    try {
			tb.latch.await();
		} catch (InterruptedException e) {
			System.out.println("文件传输失败");
			e.printStackTrace();
		}
	    
	    System.out.println("文件传输结束");
	    long sentEndTime = System.currentTimeMillis();
	    System.out.println("文件发送耗时：" + (sentEndTime - sentStartTime) + "ms");
	}
	
	public static void receiveMain() {
		
		
		Constants.TASK_TYPE = "RES";
		System.out.println("输入文件保存目录:");
		String savePath = scan.next();
		
		
		//接收协议
		System.out.println("正在建立连接...");
		ProtocolServer ps = new ProtocolServer();
		Protocol p = ps.receiveProtocol();
		
		savePath += "/" + p.getFileName();
		
		FileInfoReader fr = new FileInfoReader(savePath);
		FileEntity fe = fr.getFileEntity(p.getSize());

		long receiveStartTime = System.currentTimeMillis();
		
		System.out.println("正在接收数据...");
		ThreadBatch tb = new ThreadBatch(fe);
		
		tb.pollAndExecute(); //轮询channel并执行
		
		try {
			tb.latch.await();
		} catch (InterruptedException e) {
			System.out.println("文件接收失败");
			e.printStackTrace();
		}
		
		System.out.println("文件接收成功");
		long receiveEndTime = System.currentTimeMillis();
		System.out.println("接收文件耗时：" + (receiveEndTime - receiveStartTime) + "ms");
	}
	
	//发送：568ms 接收：548ms

}
